<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { EtlTaskVO } from '@/service/api/dataplatform/etl';
import { getEtlTaskList, deleteEtlTask, executeEtlTask } from '@/service/api/dataplatform/etl';
import EtlTaskOperateDrawer from './modules/etl-task-operate-drawer.vue';
import EtlInstanceDrawer from './modules/etl-instance-drawer.vue';

defineOptions({
  name: 'DataPlatformEtl'
});

const loading = ref(false);
const tableData = ref<EtlTaskVO[]>([]);
const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
});

const operateDrawerRef = ref<InstanceType<typeof EtlTaskOperateDrawer>>();
const instanceDrawerRef = ref<InstanceType<typeof EtlInstanceDrawer>>();

/** 查询列表 */
async function getList() {
  loading.value = true;
  try {
    const { data } = await getEtlTaskList(queryParams);
    tableData.value = data.rows;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
}

/** 搜索 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置 */
function resetQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 新增 */
function handleAdd() {
  operateDrawerRef.value?.open('add');
}

/** 编辑 */
function handleEdit(row: EtlTaskVO) {
  operateDrawerRef.value?.open('edit', row.id);
}

/** 删除 */
async function handleDelete(row: EtlTaskVO) {
  window.$dialog?.warning({
    title: '提示',
    content: `确认删除ETL任务"${row.name}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      await deleteEtlTask(row.id);
      window.$message?.success('删除成功');
      getList();
    }
  });
}

/** 执行任务 */
async function handleExecute(row: EtlTaskVO) {
  window.$dialog?.info({
    title: '提示',
    content: `确认执行ETL任务"${row.name}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { data: instanceId } = await executeEtlTask(row.id);
      window.$message?.success(`任务已开始执行，实例ID: ${instanceId}`);
      instanceDrawerRef.value?.open(row.id);
    }
  });
}

/** 查看实例 */
function handleViewInstances(row: EtlTaskVO) {
  instanceDrawerRef.value?.open(row.id);
}

// 初始化
getList();
</script>

<template>
  <div class="h-full">
    <NCard title="ETL任务管理" :bordered="false" class="h-full rounded-8px shadow-sm">
      <div class="h-full flex-col">
        <!-- 操作栏 -->
        <NSpace class="pb-12px">
          <NButton type="primary" @click="handleAdd">
            <template #icon>
              <icon-ic-round-plus class="text-icon" />
            </template>
            新增ETL任务
          </NButton>
          <NButton @click="handleQuery">
            <template #icon>
              <icon-ic-round-search class="text-icon" />
            </template>
            查询
          </NButton>
          <NButton @click="resetQuery">
            <template #icon>
              <icon-ic-round-refresh class="text-icon" />
            </template>
            重置
          </NButton>
        </NSpace>

        <!-- 表格 -->
        <NDataTable
          :loading="loading"
          :columns="[
            { key: 'id', title: 'ID', width: 80 },
            { key: 'name', title: '任务名称', minWidth: 150, ellipsis: { tooltip: true } },
            { 
              key: 'taskType', 
              title: '任务类型', 
              width: 100,
              render: (row: EtlTaskVO) => h(NTag, { type: row.taskType === 'FULL' ? 'success' : 'primary' }, { default: () => row.taskType === 'FULL' ? '全量' : '增量' })
            },
            { key: 'sourceName', title: '源数据源', minWidth: 120, ellipsis: { tooltip: true } },
            { key: 'targetName', title: '目标数据源', minWidth: 120, ellipsis: { tooltip: true } },
            { 
              key: 'status', 
              title: '状态', 
              width: 80,
              render: (row: EtlTaskVO) => h(NTag, { type: row.status === 1 ? 'success' : 'default' }, { default: () => row.status === 1 ? '启用' : '禁用' })
            },
            { key: 'createTime', title: '创建时间', width: 160 },
            {
              key: 'actions',
              title: '操作',
              width: 280,
              fixed: 'right',
              render: (row: EtlTaskVO) => h(NSpace, {}, {
                default: () => [
                  h(NButton, { text: true, type: 'primary', onClick: () => handleExecute(row) }, { default: () => '执行' }),
                  h(NButton, { text: true, type: 'primary', onClick: () => handleViewInstances(row) }, { default: () => '实例' }),
                  h(NButton, { text: true, type: 'primary', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
                  h(NButton, { text: true, type: 'error', onClick: () => handleDelete(row) }, { default: () => '删除' })
                ]
              })
            }
          ]"
          :data="tableData"
          :bordered="true"
          :single-line="false"
          class="flex-1-hidden"
        />

        <!-- 分页 -->
        <NPagination
          v-model:page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :item-count="total"
          :page-sizes="[10, 20, 50, 100]"
          show-size-picker
          class="mt-12px justify-end"
          @update:page="getList"
          @update:page-size="getList"
        />
      </div>
    </NCard>

    <!-- 操作抽屉 -->
    <EtlTaskOperateDrawer ref="operateDrawerRef" @success="getList" />

    <!-- 实例抽屉 -->
    <EtlInstanceDrawer ref="instanceDrawerRef" />
  </div>
</template>
